<template>
  <!-- 图标选择 -->
  <div ref="iconSelectRef" style="width: 100%;">
    <el-popover :visible="popoverVisible" placement="bottom-end" :width="width">
      <template #reference>
        <el-input class="reference" v-model="selectedIcon" readonly placeholder="点击选择图标"
          @click="popoverVisible = !popoverVisible">
          <template #prepend>
            <el-icon>
              <component :is="selectedIcon" v-if="selectedIcon" />
            </el-icon>
          </template>
          <template #suffix>
            <el-icon :style="{
              transform: popoverVisible ? 'rotate(180deg)' : 'rotate(0)',
              transition: 'transform .5s',
            }" @click="popoverVisible = !popoverVisible">
              <ArrowDown />
            </el-icon>
          </template>
        </el-input>
      </template>

      <!-- 下拉选择弹窗 -->
      <div ref="popoverContentRef">
        <el-scrollbar height="300px">
          <ul class="icon-container">
            <li v-for="icon in epIcons" :key="icon" class="icon-item" @click="selectIcon(icon)">
              <el-icon>
                <component :is="icon" />
              </el-icon>
            </li>
          </ul>
        </el-scrollbar>
      </div>
    </el-popover>
  </div>
</template>

<script setup>
import * as ElIcons from '@element-plus/icons-vue'
import { onClickOutside } from '@vueuse/core'
import { ref, toRef } from 'vue'
const props = defineProps({
  modelValue: {
    type: String,
    require: false,
    default: ''
  },
  width: {
    type: Number,
    require: false,
    default: 360
  }
})
const emit = defineEmits(['update:modelValue'])
const selectedIcon = toRef(props, 'modelValue')
const iconSelectRef = ref(null)
const popoverContentRef = ref(null)
const popoverVisible = ref(false) // 弹窗显示状态
const epIcons = Object.keys(ElIcons) // Element Plus图标集合

// 选择图标
const selectIcon = (iconName) => {
  console.log(iconName)
  emit('update:modelValue', iconName)
  popoverVisible.value = false
}

// 点击容器外的区域关闭弹窗 VueUse onClickOutside
onClickOutside(iconSelectRef, () => (popoverVisible.value = false), {
  ignore: [popoverContentRef]
})
</script>

<style lang="scss" scoped>
.reference :deep(.el-input__wrapper),
.reference :deep(.el-input__inner) {
  cursor: pointer;
}

.icon-container {
  display: flex;
  flex-wrap: wrap;

  .icon-item {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px;
    margin: 4px;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;
  }

  .icon-item:hover {
    border-color: #4080ff;
    scale: 1.2;
  }
}
</style>
